import  { createContext,useState,useEffect } from "react";
import localStorage from '@/utils/localStorage'
const AuthContext = createContext({});

const AuthProvider = ({children}:any)=>{
  const [state,setState] = useState<any>(null)

  useEffect(()=>{
    const loadLocalStorageDate =async()=>{
      let data:any = {};
      setState({...state,user:data?.user,token:data?.token});
    }
    loadLocalStorageDate();
  },[])

  const loginOut=()=>{
    return new Promise(function(resolve, reject){
      try{
        let data = {
          token:null,
          user:null
        }
        setState(data);
        resolve(true);
      }catch(err) {
        reject(false);
      }
    })
    
    // 退出登录
  }

  const login=()=>{
    return new Promise(function(resolve, reject){
      try{
        let data = {
          token:'boonook',
          user:{
            name:'朱秀武',
            id:"145385"
          }
        }
        localStorage.get('BOONOOK');
        setState(data);
        resolve(true);
      }catch(err) {
        reject(false);
      }
    })
    
    // 退出登录
  }

  return (
    <AuthContext.Provider value={{state,setState,loginOut,login}}>
      {children}
    </AuthContext.Provider>
  )
}

export {AuthContext,AuthProvider};